﻿using UnityEngine;

namespace Panty
{
#if UNITY_EDITOR
    using UnityEditor;
    [CustomPropertyDrawer(typeof(PnShowSpriteAttribute))]
    public class ShowSpriteDrawer : PropertyDrawer
    {
        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            float height = base.GetPropertyHeight(property, label);
            if (property.propertyType == SerializedPropertyType.ObjectReference)
            {
                var previewTexture = AssetPreview.GetAssetPreview(property.objectReferenceValue);
                if (previewTexture != null) height += EditorGUIUtility.singleLineHeight * 2;
            }
            return height;
        }
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(position, label, property);
            if (property.propertyType == SerializedPropertyType.ObjectReference)
            {
                EditorGUI.PropertyField(position, property, label);
                if (property.objectReferenceValue != null)
                {                    
                    var previewTexture = AssetPreview.GetAssetPreview(property.objectReferenceValue);
                    if (previewTexture != null)
                    {
                        Rect previewRect = new Rect()
                        {
                            x = position.x + EditorGUI.IndentedRect(position).x - position.x,
                            y = position.y + EditorGUIUtility.singleLineHeight,
                            width = position.width,
                            height = EditorGUIUtility.singleLineHeight * 2
                        };
                        GUI.Label(previewRect, previewTexture);
                    }
                }
            }
            EditorGUI.EndProperty();
        }
    }
    public class PnShowSpriteAttribute : PropertyAttribute { }
#endif
}
